package com.zhuxiang.test5;

import java.io.*;
import java.net.Socket;

/**
 * 客户端接收线程类
 */
public class ClientReceiveThread extends Thread {
    private Socket s;
    public ClientReceiveThread(Socket s){
        this.s = s;
    }

    @Override
    public void run(){
        BufferedReader br = null;

        try {
            br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            String str2 = "";
            while ((str2 = br.readLine()) != null){
                System.out.println("file".equalsIgnoreCase(str2)?"":str2);
                if ("file".equalsIgnoreCase(str2)){
                    String fileName = br.readLine();
                    receiveFile(fileName);
                }
            }
            System.out.println("file".equalsIgnoreCase(str2)?"":str2);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
    }

    /**
     * 根据文件名接收文件，写到D://client文件夹下
     * @param fileName
     * @throws IOException
     */
    private  void receiveFile(String fileName) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
        BufferedOutputStream bos = null;
        bos = new BufferedOutputStream(new FileOutputStream("D://client//"+System.currentTimeMillis()+""+fileName));
        byte[] bytes = new byte[1024*2];
        int len = 0;
        while ((len = bis.read(bytes)) != -1){
            bos.write(bytes,0,len);
            if (len < bytes.length){
                break;
            }
        }
        bos.flush();
    }
}
